
import java.io.IOException;
import java.io.PrintWriter;
import java.security.GeneralSecurityException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.docs.*;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Link;
import com.google.gdata.data.docs.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.net.URL;

import javax.servlet.http.Cookie;

/**
 *
 * @author Flaviano
 */
public class lista extends HttpServlet {

    PrintWriter out = null;
    String singleUseToken;// = AuthSubUtil.getTokenFromReply(httpServletRequest.getQueryString());
    String sessionToken;// = AuthSubUtil.exchangeForSessionToken(singleUseToken, null);
    Cookie cookieToken = null;
    DocsService client = new DocsService("yourCo-yourAppName-v1");

    public void printEntry(DocumentListEntry entry) {
        //PrintWriter out = null;// = response.getWriter();
        String resourceId = entry.getResourceId();
        String docType = entry.getType();

        out.println("</p> " + entry.getTitle().getPlainText() + "' (" + docType + ")");
        out.println("<br>  link to Google Docs: " + entry.getDocumentLink().getHref());
        out.println("<br>  resource id: " + resourceId);
        out.println("<br>  doc id: " + entry.getDocId());
        // print the parent folder the document is in
        if (!entry.getParentLinks().isEmpty()) {
            out.println("<br>  Parent folders: ");
            for (Link link : entry.getParentLinks()) {
                out.println("<br>    --" + link.getTitle() + " - " + link.getHref());
            }
        }

        // print the timestamp the document was last viewed
        DateTime lastViewed = entry.getLastViewed();
        if (lastViewed != null) {
            out.println("<br>  last viewed: " + lastViewed.toUiString());
        }

        // print who made the last modification
        LastModifiedBy lastModifiedBy = entry.getLastModifiedBy();
        if (lastModifiedBy != null) {
            out.println("<br>  updated by: " +
                    lastModifiedBy.getName() + " - " + lastModifiedBy.getEmail());
        }

        // Files such as PDFs take up quota
        if (entry.getQuotaBytesUsed() > 0) {
            System.out.println("<br>Quota used: " + entry.getQuotaBytesUsed() + " bytes");
        }

        // print other useful metadata
        out.println("<br>  last updated: " + entry.getUpdated().toUiString());
        out.println("<br>  viewed by user? " + entry.isViewed());
        out.println("<br>  writersCanInvite? " + entry.isWritersCanInvite().toString());
        out.println("<br>  hidden? " + entry.isHidden());
        out.println("<br>  starred? " + entry.isStarred());
        out.println("<br>  trashed? " + entry.isTrashed() + "</p>");
        out.println();
    }

    public void showAllDocs() throws IOException, ServiceException {
        client.setAuthSubToken(cookieToken.getValue(), null);
        URL feedUri = new URL("http://docs.google.com/feeds/default/private/full/");
        DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
        for (DocumentListEntry entry : feed.getEntries()) {
            printEntry(entry);
        }
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, GeneralSecurityException, AuthenticationException {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        //le os Cookies do usuario verificando se ha token de segurança
        //String nomeArquivo = request.getParameter("token");
        String cookieName = "cookieToken";//nome do cookie
        //quando não existe cookies associados, o método getCookies() retorna um valor null
        Cookie listaPossiveisCookies[] = request.getCookies();//lista de cookie
        if (listaPossiveisCookies != null) {
            int numCookies = listaPossiveisCookies.length;
            for (int i = 0; i < numCookies; ++i) {
                if (listaPossiveisCookies[i].getName().equals(cookieName)) { //procura pelo cookie
                    cookieToken = listaPossiveisCookies[i];
                    break;
                }
            }
            if (cookieToken != null) {
                try {
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>SEDCloud</title>");
                    out.println("</head>");
                    out.println("<body>");
                    out.println("<h1>Servlet lista at " + request.getContextPath() + "</h1>");
                    try {
                        showAllDocs();
                    } catch (ServiceException ex) {
                        Logger.getLogger(lista.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    out.println("</body>");
                    out.println("</html>");
                } finally {
                    out.close();
                }
            } else {
                response.sendRedirect("http://localhost:8084/GDataApi3/index.jsp");
            }
        }
    }

// <editor-fold defaultstate="collapsed" desc="Métodos HttpServlet. Clique no sinal de + à esquerda para editar o código.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(lista.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AuthenticationException ex) {
            Logger.getLogger(lista.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(lista.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AuthenticationException ex) {
            Logger.getLogger(lista.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
